package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.dto.AddressDto;
import com.itheima.mapper.AddressMapper;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Boolean defaultAddress(String id) {

        addressMapper.setAllAddress();
        boolean res = addressMapper.defaultAddress(id);
        return res;

    }

    @Override
    public Address getDefaultAddress() {
        Address defaultAddress = addressMapper.getDefaultAddress();
        return defaultAddress;
    }

    @Override
    public List<Address> getList() {
        List<Address> list = addressMapper.getList();

        return list;
    }

    @Override
    public Address getAddressById(String id) {
        Address address = addressMapper.getAddressById(id);
        return address;
    }

    @Override
    public boolean remove(String ids) {

        if (StringUtils.isEmpty(ids)) {
            return true;
        }
        String[] split = ids.split(",");
        if (split.length == 0) {
            throw new RuntimeException("入参不能为空");
        }
        List<String> list = Arrays.asList(split);
        Boolean res = addressMapper.removeAddressById(list);

        return res;
    }

    @Override
    public boolean add(AddressDto addressDto) {

        Address address=new Address();
        BeanUtils.copyProperties(addressDto,address);
        String id = IdUtil.getSnowflakeNextIdStr();
        address.setId(id);
        address.setUserId(ThreadLocalIUtil.getId());
        boolean add = addressMapper.add(address);
        return  add;
    }

    @Override
    public boolean update(AddressDto addressDto) {

        boolean update = addressMapper.update(addressDto);
        return update;
    }
}
